Repository navigation
fix(relay): don't re-run an agent resume against a relay that never held the terminal (STA-5698) - #16989
fix(relay): don't re-run an agent resume against a relay that never held the terminal (STA-5698)#16989brennanb2025 wants to merge 1 commit into
Conversation
…eld the terminal When a stable pane's reattach fails with positive absence, the fallback re-spawns using the original request's spawn options, replaying `launchAgent` / resume argv / `command`. On a cold restore that is right. After a relay daemon replacement it is not: the binding may name a PTY from a previous daemon whose shell is still alive as an orphan, so the replay starts a SECOND agent against the same worktree. `relay.status` already reports `uptimeMs`. A daemon whose uptime is shorter than the age of the binding it just answered about demonstrably never owned that binding, so its positive absence is `unverifiable`, not `exited`. On that verdict the fallback still spawns a shell — the spawn is never gated — but drops the startup intent and sets the existing `agentResumeUnavailable` flag so the pane shows the resume-unavailable banner instead of claiming the old session came back. Loss of contact produces no verdict: a missing host RPC, a rejected or timed-out `relay.status`, a non-object reply, an absent or unusable `uptimeMs`, and a binding nothing can date all leave today's behavior exactly as-is. Client-side policy only — no new wire field and no new stream opcode. STA-5698
📝 WalkthroughWalkthroughThe change detects when an SSH PTY relay was replaced by comparing relay uptime with the persisted binding age. When confirmed, stable-pane fallback removes startup intent and marks the spawn with Merge Risk: 🟡 Moderate · up to When a replacement relay is detected, the change creates a plain shell instead of replaying agent startup, but the current implementation can first mark the existing SSH PTY as exited and the runtime path does not return the resume-unavailable indication. This can misclassify a live terminal and leave some users without the expected recovery message, so follow-up is needed before merge. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed, on-topic, and covers the problem, implementation, rationale, linked issue, behavior changes, testing, limitations, compatibility, and review risks. It does not reproduce every template heading or checklist item, but the required substantive information is mostly present.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 68b383b2-5d16-4631-927c-8740617972c6
📒 Files selected for processing (6)
src/main/ipc/pty/ipc/spawn-commit.tssrc/main/ipc/pty/pane/relay-replacement-resume-suppression.tssrc/main/ipc/pty/pane/stable-owner.tssrc/main/ipc/pty/pane/stable-pane-relay-age-resume-suppression.test.tssrc/main/ipc/pty/runtime/spawn-commit.tssrc/main/providers/pty-spawn-result.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| if (isSshPtyAbsentFromRelayError(error)) { | ||
| args.onRelayPositiveAbsence?.() | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- applicable repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print
printf '%s\n' '--- SSH execution boundary ---'
cat -n docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner outline ---'
ast-grep outline src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- changed path and direct flow ---'
sed -n '220,325p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- onPtyExit definitions and callers ---'
rg -n -A8 -B8 'onPtyExit|isSshPtyAbsentFromRelayError|spawnForStablePane|attachStablePaneOwner' src/mainRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- convention file headers ---'
find /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4 -type f -name '*.md' -print0 |
while IFS= read -r -d '' f; do
printf '\n### %s\n' "$f"
head -5 "$f"
done
printf '%s\n' '--- SSH execution boundary ---'
sed -n '1,220p' docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner imports and flow ---'
sed -n '1,90p' src/main/ipc/pty/pane/stable-owner.ts
sed -n '220,325p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- focused definitions ---'
rg -n -A35 -B12 'class OrcaRuntimeService|onPtyExit\s*\(' src
printf '%s\n' '--- focused diff ---'
git diff -- src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- stable-owner tests ---'
find src/main -type f \( -name '*stable-owner*.test.ts' -o -name '*pty*persisted*repair*.test.ts' \) -printRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- knowledge files ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print
printf '%s\n' '--- SSH boundary terms ---'
rg -n -A4 -B4 'loss of contact|unverifiable|live|exited|relay' docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner exact source ---'
rg -n 'isSshPtyAbsentFromRelayError|onPtyExit|spawnForStablePane|attachStablePaneOwner|relay|unverif' src/main/ipc/pty/pane/stable-owner.ts
sed -n '1,80p' src/main/ipc/pty/pane/stable-owner.ts
sed -n '220,320p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- runtime implementation location ---'
rg -l 'class OrcaRuntimeService' src/main
rg -n -A45 -B10 '^[[:space:]]*onPtyExit[[:space:]]*\(' src/main/runtime
printf '%s\n' '--- focused diff ---'
git diff --stat -- src/main/ipc/pty/pane/stable-owner.ts
git diff -U20 -- src/main/ipc/pty/pane/stable-owner.tsRepository: stablyai/orca
Length of output: 24421
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- attachStablePaneOwner complete flow ---'
sed -n '185,285p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- onPtyExit complete decision flow ---'
sed -n '15960,16090p' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- liveness verdict implementation ---'
rg -n -A30 -B8 'getPtyLivenessVerdict|markPtyLivenessUnverifiable|SSH_EXIT_UNCONFIRMED_REASON' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- relay absence error contract and provider path ---'
rg -n -A20 -B10 'isSshPtyAbsentFromRelayError|SshPtyAbsent|ABSENT_FROM_RELAY|absent from relay' src/main
printf '%s\n' '--- focused persisted-repair cases ---'
rg -n -A18 -B18 'owner_unverified|replacement relay|young|onPtyExit.*not|positive absence|relay' src/main/ipc/pty-persisted-incarnation-repair.test.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- replacement-relay suppression implementation ---'
cat -n src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
printf '%s\n' '--- all relay age/replacement symbols ---'
rg -n -A12 -B12 'relayAge|relay age|replacement relay|relay replacement|replayed intent|spawnWithoutReplayedIntent|grace|young' src/main src/relay
printf '%s\n' '--- SSH provider lifecycle and relay identity ---'
sed -n '200,275p' src/main/providers/ssh-pty-session-reattach.ts
sed -n '1,130p' src/main/providers/ssh-pty-errors.ts
rg -n -A18 -B18 'restart|reconnect|generation|relay.*start|startedAt|createdAt|age' src/main/ssh src/main/providers src/relay | head -300
printf '%s\n' '--- relevant conventions and learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src-main-pty.mdRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- suppression helper ---'
wc -l src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
cat -n src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
printf '%s\n' '--- stable pane spawn context and all age-related fields ---'
rg -n -A12 -B12 'StablePaneSpawnContext|relayAnsweredAbsent|spawnWithoutReplayedIntent|age|generation|replacement' src/main/ipc/pty/pane src/main/providers/ssh-pty-session-reattach.ts
printf '%s\n' '--- reattach error path ---'
sed -n '215,265p' src/main/providers/ssh-pty-session-reattach.ts
printf '%s\n' '--- focused persisted-repair tests ---'
sed -n '330,510p' src/main/ipc/pty-persisted-incarnation-repair.test.ts
printf '%s\n' '--- focused relay-absence tests ---'
sed -n '1,110p' src/main/providers/ssh-pty-relay-absence-verdict.test.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- focused relay-absence test file ---'
wc -l src/main/ipc/pty/pane/stable-pane-relay-absence-respawn.test.ts
cat -n src/main/ipc/pty/pane/stable-pane-relay-absence-respawn.test.ts
printf '%s\n' '--- stable-owner context declaration ---'
rg -n -A35 -B8 'type StablePaneSpawnContext|interface StablePaneSpawnContext|onRelayPositiveAbsence' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- exact exit surface effects ---'
sed -n '16080,16180p' src/main/runtime/orca-runtime.tsRepository: stablyai/orca
Length of output: 18101
Classify young replacement relays as unverifiable before exit handling. attachStablePaneOwner calls runtime.onPtyExit(..., 0, ...) before spawnWithoutReplayedIntent checks relay.status.uptimeMs. This treats a possibly live SSH PTY as exited. Add a test that asserts onPtyExit is not called.
Source: Coding guidelines
There was a problem hiding this comment.
Judged this from the code rather than the label, and I think it's real as a contract gap — but it is pre-existing, not introduced here, and the fix is bigger than the thread implies. Leaving it open for @brennanb2025 rather than resolving.
The ordering claim is accurate. At head 24614bd:
stable-owner.ts:249-251— the new hook only recordsrelayAnsweredAbsent.stable-owner.ts:262—runtime?.onPtyExit(owner.ptyId, 0, owner.incarnationId)fires immediately after, inside the samecatch.stable-owner.ts:305-307—spawnWithoutReplayedIntent(and thereforeansweringRelayPredatesBinding→relay.status.uptimeMs) runs only afterattachStablePaneOwnerhas already returnednull.
So the exit is published before anything has evaluated whether the answering relay could have owned the binding.
Why the exit code matters, and it isn't cosmetic. In orca-runtime.ts:
:15992preservesAbnormalSshSurfacerequiresexitCode < 0. The call site passes0, so it is false.:16002is therefore skipped —markPtyLivenessUnverifiable(ptyId, SSH_EXIT_UNCONFIRMED_REASON)never runs.:16012processDeathCertified = exitCode >= 0 || …is true, soreconcileAgentStatusForEndedProcessFnruns and the agent status is reconciled as ended.
onPtyExit(ptyId, 0, …) is a certified clean death. That is exited.
Which is the one verdict this case is not allowed to be. docs/reference/ssh-execution-boundary.md, "Distinguishing unverifiable from exited": "A stale event, an event for a superseded incarnation, or one quiet terminal with no host evidence does not [establish exited]." A relay whose uptime is shorter than the binding's age is a superseded incarnation by construction — that is the PR's own premise, stated verbatim at relay-replacement-resume-suppression.ts:76-83 ("its positive absence is unverifiable rather than exited"). The code acts on that premise for the resume intent and not for the liveness verdict.
Two things the thread gets wrong, though.
-
It isn't a regression from this PR.
:262is unchanged onmainand fires for everyisPtyAlreadyGoneError. This PR adds the knowledge that a subset of those absences is unverifiable; it does not make the verdict worse than it already was. -
"Add a test that asserts
onPtyExitis not called" is not the right assertion, and the naive fix regresses something else. SkippingonPtyExitleaves the runtime holding a binding no relay will ever answer for. And unconditionally passingexitCode < 0for everySshPtyAbsentFromRelayErrorwould mark genuinely-exited SSH PTYsunverifiable, which feedsverifyUnstoppedPtys(unstopped-pty-verification.ts:17) and can block worktree removal. The correct shape is: still retire the surface, but chooseexitCode 0vs-1based on the age probe — which means hoistingansweringRelayPredatesBindingabove:262and awaiting up toRELAY_AGE_STATUS_TIMEOUT_MS(2s) inside the teardown path. That is a real latency and design change, and it is why the "heavy lift" tag is the accurate part of this comment.
One thing worth acting on regardless of the above: every case in stable-pane-relay-age-resume-suppression.test.ts passes runtime: undefined (:63, :217), so runtime?.onPtyExit is a no-op in all 12 tests. Whatever this PR decides the verdict should be, nothing currently pins it.
Also unrelated to this thread but in the same file — answeringRelayPredatesBinding is named backwards. It returns true when age > uptimeMs + slack, i.e. when the relay started after the binding and therefore does not predate it. The behavior is correct and the test names use "predates" in the correct English sense (…test.ts:138 pairs "predates the binding" with olderRelay and expects a replay), so the identifier is the sole outlier. Worth renaming before someone inverts the gate reading it.
There was a problem hiding this comment.
@.wk-scratch/reply-16989-a.md
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
if [ -f .wk-scratch/reply-16989-a.md ]; then
cat .wk-scratch/reply-16989-a.md
else
printf '%s\n' 'Referenced draft does not exist in this checkout.'
fd -a '^reply-16989-a\.md$' . || true
fiLength of output: 415
@brennanb2025, .wk-scratch/reply-16989-a.md is not present in this checkout. Please paste the draft content or provide an accessible file path.
You are interacting with an AI system.
There was a problem hiding this comment.
This describes #16989's tree only. Nothing here survives the PR's closure — and main's onPtyExit(…, 0, …) is correct as written. Recording the check so it is not rediscovered.
The reported ordering does not exist on main. At origin/main (94e7586665) stable-owner.ts is 293 lines, the exit is at :255, and spawnWithoutReplayedIntent / relay.status.uptimeMs appear nowhere in the repo — grep -rn answeringRelayPredatesBinding src/ returns zero hits. The "publishes before the gate" relationship is created by this PR, so it dies with it.
The ordering is real inside the PR. attachStablePaneOwner publishes the exit and then return nulls; the gate runs one frame later, in spawnForStablePane. So the PR suppresses the replayed startup intent but never retracts the exit it already published. Two aggravators, also PR-local: kill.ts:79-88 publishes -1 for the identical isPtyAlreadyGoneError predicate, and adopt-stable.ts:60 calls attachStablePaneOwner directly, so that caller never reaches the gate at all.
On main the 0 is not a coercion — it is a host-verified absence. By the time line 255 runs, the two non-evidence classes have already been diverted above it:
if (error instanceof TerminalSessionOwnerUnverifiedError) { // :235
throw new Error('terminal_pane_owner_unverified')
}
if (isDaemonEndpointGoneError(error)) { // :239
throw new TerminalHostGoneError()
}
if (!isPtyAlreadyGoneError(error)) { // :242
throw error
}Each remaining arm of isPtyAlreadyGoneError (provider/liveness.ts:58-67) is positive evidence from the owning host on this path:
SshPtyAbsentFromRelayError— raised only atssh-pty-session-reattach.ts:238, after:229diverts identity mismatch ("the id names a LIVE PTY owned by another pane"). Pinned both directions byssh-pty-relay-absence-verdict.test.ts./PTY ".+" not found/i— produced only bysrc/relay/pty-handler.ts, i.e. the relay answering. On the attach path it is converted to the class above before any caller sees it; the other four throw sites arecloseStartupQueryAuthority,sendSignal,getCwd,getInitialCwd, none of which are on this path./Session not found/i—SessionNotFoundError, reachable here only from a received daemon response (decodeDaemonResponseError) or fromresolution.kind === 'absent'inDaemonSessionOwnerResolver.spawnAttachOnly, which routeskind === 'unknown'toTerminalSessionOwnerUnverifiedErrorinstead.
A transport failure cannot reach line 255: stable-pane-relay-absence-respawn.test.ts:98-107 pins that a lost link, a request timeout, and a bare SSH_SESSION_EXPIRED all rethrow and keep the binding.
So the downstream composition is right. resolveUnreportedExitCause(0) yields { kind: 'unknown', reason: 'cause_unreported' } — "the reporting host did not say why", which is exactly what a relay-confirmed absence with no status tells us. processDeathCertified (orca-runtime.ts:16012) becomes true, correct for a verified absence, and preservesAbnormalSshSurface (:15992) correctly does not mark the pane unverifiable. Switching main to -1 would be the regression, not the fix: it would publish stop_unverified and markPtyLivenessUnverifiable for a process the host positively reported gone.
Leaving this thread open per the reviewer's request. No main PR was opened, because there is nothing on main to change.
There was a problem hiding this comment.
@brennanb2025, agreed on the scope correction.
onPtyExit(..., 0, ...) is correct on main. On main, the attach path has only host-verified absence cases at that point. The replacement-relay age gate does not exist there.
The finding is limited to #16989. This PR adds a new fact that can change the absence verdict: a relay younger than the binding could not have owned that binding. The current flow publishes the certified exit before it evaluates that fact.
No main follow-up is needed. The open thread should remain scoped to the PR-local ordering and its direct callers, including adopt-stable.ts.
🐇🔍
✏️ Learnings added
Learnt from: brennanb2025
Repo: stablyai/orca PR: 16989
File: src/main/ipc/pty/pane/stable-owner.ts:249-251
Timestamp: 2026-08-28T14:53:40.394Z
Learning: In the Orca stable-pane attach path on main, `runtime.onPtyExit(ptyId, 0, incarnationId)` follows host-verified PTY absence and is correct. PR `#16989` adds replacement-relay age detection after `attachStablePaneOwner` returns; when the answering SSH relay is younger than the persisted binding, that PR-local ordering can publish a certified exit before the new relay-age evidence classifies the absence as unverifiable. Any fix must be scoped to the PR behavior, not main.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
You are interacting with an AI system.
| if (ctx.isClaudeLaunch && !ctx.stablePaneOwner && !ctx.result.agentResumeUnavailable) { | ||
| markClaudePtySpawned(ctx.result.id) | ||
| } | ||
| if (args.telemetry && !ctx.stablePaneOwner) { | ||
| // Why: a suppressed resume produced a plain shell, so there is no agent launch to report. | ||
| if (args.telemetry && !ctx.stablePaneOwner && !ctx.result.agentResumeUnavailable) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Return agentResumeUnavailable from the runtime response. The response whitelist at Line 288 omits the flag, while the reservation result at Line 302 retains it. The initial runtime caller cannot show the resume-unavailable banner.
There was a problem hiding this comment.
Real, and this is the gap @brennanb2025 already flagged in the PR description — the paired/runtime path gets the suppression but not the surfacing. Two corrections though: the stated fix is incomplete, and the reason it hasn't been done is not a wire constraint.
The omission is real. At head 24614bd:
runtime/spawn-commit.ts:288-301buildsresponseas an explicit whitelist;agentResumeUnavailableis not in it.:302-310resolvePaneSpawnReservationspreads...ctx.result, so the reservation path does carry it. That asymmetry is exactly as described.- By contrast
ipc/spawn-commit.ts:196-217builds its response with...ctx.result(a spread), which is why the renderer banner works on the IPC path at all —ipc-pty-connect-result.ts:36,52→apply-reattach-payload.ts:281/fresh-spawn-start.ts:212.
But adding it at Line 288 alone does nothing. There is a second whitelist downstream: runtime/spawn.ts:20-34 toRuntimeSpawnReply re-projects the result into {id, incarnationId, wslDistro, stablePaneOwner, agentSessionEnsure} and is applied at :84, :88, :95 and :98. A field added at :288 is dropped one frame later. Both have to change or the fix is dead code with a passing-looking test.
And it still wouldn't reach a user. ptyController.spawn (runtime/controller.ts:43) is consumed by OrcaRuntimeService.createTerminal (orca-runtime.ts:28975), whose result type is RuntimeTerminalCreate (shared/runtime-terminal-contracts.ts:245-258). That type has no such field either, and its consumers are the CLI / automation / mobile terminal create surface — there is no banner there to show. So the honest fix is four layers, not one: spawn-commit.ts:288 → toRuntimeSpawnReply → RuntimeTerminalCreate (plus shared/runtime-client-export-parity.test.ts:136) → createTerminal. "Quick win" is the wrong tag.
On the wire question — the stated blocker doesn't hold. docs/reference/remote-wire-compatibility.md Rule 1 is explicit: "a new optional JSON field on an existing frame is safe … Every JSON payload is parsed with a decoder that ignores unknown keys." An optional agentResumeUnavailable?: true on the terminal create result is Rule 1, not Rule 2 — Rule 2 is about stream opcodes, which decoders drop silently, and none is involved here. The Rule 1 caveat also holds cleanly in this direction: a new client against an old host sees the field absent and shows no banner, which is precisely today's behavior, so absence degrades to the status quo rather than to a wrong claim. This is not a reason to leave it out.
Why it's more than "Minor". Without it, orca terminal create with a resume/--agent against an SSH worktree can return success while main has deliberately dropped the startup intent, and the caller has no way to tell. That is the ssh-execution-boundary.md anti-pattern — "an operation … that reports success may not have run — check the durable state it should have changed rather than trusting the return" — applied to Orca's own API rather than to a shell command.
Cheapest correct shape: RuntimeTerminalCreate already carries warning?: string (runtime-terminal-contracts.ts:255), which the CLI already surfaces. Populating that on a suppressed resume gets the information to the automation caller with no new field at all — while a dedicated optional boolean is still available and still Rule 1-safe if a machine-readable signal is wanted.
Leaving open — this needs a scope call from @brennanb2025, not a resolve.
There was a problem hiding this comment.
@.wk-scratch/reply-16989-b.md
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
fd -H -a '^reply-16989-b\.md$' . -x sh -c 'echo "===== $1 ====="; cat "$1"' sh {}Length of output: 251
@brennanb2025, the search completed with no matches. The referenced file is not present in this checkout. Please paste the reply content so I can evaluate the scope decision.
You are interacting with an AI system.
There was a problem hiding this comment.
This describes #16989's tree only, and the omission it names is a deliberate main decision. Nothing here survives the PR's closure. Recording the check so it is not rediscovered.
There is no agentResumeUnavailable on the runtime path to return. main does produce the flag — but only on the IPC path (src/main/ipc/pty/ipc/spawn-commit.ts:213-215, from ctx.codexResumeLaunch.notifyResumeUnavailable), surfaced through preload/api/pty-api.ts:70. The runtime controller has no producer, and runtime/spawn-preflight.ts:129-131 says so in as many words:
// Why: the drop still applies here, but this controller's result has no field for
// notifyResumeUnavailable — runtime/relay panes start fresh without the notice.So on main the whitelist drops nothing. Only this PR gives the runtime path a value to drop.
The one-line fix would be dead code even inside the PR. runtime/spawn.ts:20-33 toRuntimeSpawnReply is a second whitelist, between commitRuntimePtySpawn and the caller:
return {
id: result.id,
...(result.incarnationId ? { incarnationId: result.incarnationId } : {}),
...(typeof result.wslDistro === 'string' ? { wslDistro: result.wslDistro } : {}),
...(result.stablePaneOwner ? { stablePaneOwner: result.stablePaneOwner } : {}),
...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {})
}Adding the field to the response object alone would surface no banner anywhere.
The PR's stated reason for not doing it does not hold, though. The description calls adding the field to the runtime response "a wire change this ticket forbids". Per docs/reference/remote-wire-compatibility.md Rule 1, "a new optional JSON field on an existing frame is safe" — decoders .strip() unknown keys, and an older peer simply does not read it. The correct objection is not wire risk; it is that both whitelists would need the field and the runtime path has no producer for it.
What is left on main is a product gap, not a defect. A paired-runtime or mobile pane whose Codex resume falls back to a fresh session gets no "resume unavailable" notice — by the documented design quoted above. Worth a ticket if that matters. It is not a coercion bug, and it is not this PR's.
Leaving this thread open per the reviewer's request. No main PR was opened.
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline src/main/ipc/pty/runtime/spawn.ts --items all
ast-grep outline src/main/ipc/pty/runtime/spawn-preflight.ts --items all
ast-grep outline src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts --items all
ast-grep outline src/main/ipc/pty/pane/stable-owner.ts --items all
printf '\n=== Runtime reply projection ===\n'
rg -n -A35 -B5 'function toRuntimeSpawnReply|const toRuntimeSpawnReply|toRuntimeSpawnReply\s*=' \
src/main/ipc/pty/runtime/spawn.ts
printf '\n=== Runtime preflight notice contract ===\n'
rg -n -A12 -B8 'notifyResumeUnavailable|agentResumeUnavailable' \
src/main/ipc/pty/runtime/spawn-preflight.ts
printf '\n=== PR suppression producer ===\n'
rg -n -A18 -B12 'spawnWithoutReplayedIntent|agentResumeUnavailable' \
src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts \
src/main/ipc/pty/pane/stable-owner.ts
printf '\n=== Commit response projection ===\n'
rg -n -A35 -B5 'const response = \{' src/main/ipc/pty/runtime/spawn-commit.tsLength of output: 17441
@brennanb2025, the main clarification is correct. The existing runtime Codex-resume behavior does not produce agentResumeUnavailable. The spawn-preflight.ts comment documents that decision.
This PR changes the condition. spawnWithoutReplayedIntent returns agentResumeUnavailable: true at Line 144, and spawnForStablePane returns that result to the runtime flow at Lines 305-309.
Therefore, the PR-specific omission remains valid. commitRuntimePtySpawn drops the produced flag at Lines 288-301. toRuntimeSpawnReply drops it again at Lines 20-33. Adding the field only at Line 288 would not expose it to the runtime caller.
I agree that this is not a wire-compatibility blocker. I also agree that the correct fix requires both runtime response projections, plus the contract and consumer work needed to present a warning. The original “Quick win” scope was incorrect.
🐇 🔎
✏️ Learnings added
Learnt from: brennanb2025
Repo: stablyai/orca PR: 16989
File: src/main/ipc/pty/runtime/spawn-commit.ts:228-232
Timestamp: 2026-08-28T14:54:12.837Z
Learning: In `src/main/ipc/pty/runtime/spawn-preflight.ts`, the existing runtime Codex-resume drop behavior deliberately has no `notifyResumeUnavailable` result field. In PR `#16989`, `src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts` separately produces `PtySpawnResult.agentResumeUnavailable` for confirmed replacement SSH relays. Any runtime caller notification for that PR-specific flag must propagate through both `src/main/ipc/pty/runtime/spawn-commit.ts` and `src/main/ipc/pty/runtime/spawn.ts` response whitelists.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
You are interacting with an AI system.
STA-5698: three-way comparison of #16989, #16839, #16901Read the diffs rather than the titles. Verdicts below are from the code and from At a glance
#16989 — client-side age gate
Wire: none. Fixes uniquely: it is the only one of the three that needs no host-side change, so it protects users whose relay is already deployed and will not be restarted. It is also the only one whose suppression reaches the telemetry and Claude-spawn bookkeeping ( Fails to fix: the orphan itself; the Blast radius / reversibility: smallest of the three. One new module, four guard clauses, no persisted state, no wire surface. A clean #16839 — relay process identityThe relay mints a process identity at startup and publishes it on Wire: additive optional fields, so Rule 1 by construction — but it lands squarely on Rule 1's own caveat: "The field is safe only for as long as every reader treats it as optional. The moment a newer client requires it, that client is broken against every host that predates the field." This client requires it: Fixes uniquely: it is the only one with a positive proof of ownership rather than an inference — a same-relay absence stays Fails to fix: the orphan itself, the id-collision class, and — same as #16989 — the reboot case: a rebooted host runs a new relay with a new identity, so the match fails and the resume is suppressed even though nothing survived. Blast radius / reversibility: largest by a wide margin. 40 files across relay, providers, IPC, runtime, and shared types, plus a new persisted lease field. It is CONFLICTING with #16901 — relay incarnation in the idTwo production lines: Wire: Rule 3 — the host changes the content it publishes with no codec change. I checked the decoder: Fixes uniquely: it is the only one of the three that removes the id-reuse class — a reset relay minting Fails to fix: it suppresses nothing. A replacement relay still answers "absent" for Blast radius / reversibility: 2 production lines, but they change every remote PTY id, which is persisted in leases and bindings. A revert after users accumulate (Small note in passing: Are any two complementary? — Yes, and this is measurableI took #16989 and #16901 share zero files and zero mechanism. One is a client policy on They are in fact synergistic, which is the more interesting result. Once ids carry the relay incarnation, the client can read the epoch out of the binding it already holds and compare it against the answering relay's current epoch. That is a proof of replacement, with no #16989 and #16839 are genuinely mutually exclusive — four shared files, and both rewrite the same decision point in #16901 and #16839 are redundant at the relay layer — both encode relay incarnation identity, one intrinsically in the id and one as a side-channel field, and they collide in RecommendationLand #16901. Do not land #16839. Hold #16989 pending the argument below. #16901 is the only one of the three that removes a failure class rather than detecting it, it is two production lines, its wire skew is self-healing, and it is disjoint from this PR. #16839 buys a strictly better signal than #16989 at ~2.7× the diff, 40 files, an unresolved conflict with If duplicate-resume suppression is still wanted after #16894 and #16895 land, build it on #16901's epoch comparison rather than on either uptime or a side-channel identity field. The strongest argument against #16989It revives an approach that was already tried and closed for this exact defect, one day earlier, by its own author. #16843 — "fix(ssh): stop the absence fallback resuming an agent a replaced relay never held (STA-5698)" — was closed on 2026-08-27 with this rationale:
The same closing note also records that the harm could not be reproduced on Linux at all:
and that the surviving Windows case has a host-side cause and a host-side fix ( The honest counter is that #16989 is cheap and trivially revertible, and that #16894 / #16895 are still open. But that argues for landing those two, not for re-landing the inference this PR's author already rejected. Reviewed at #16989 |
Coordinator note: this PR uses the approach you already rejected in #16843I dispatched this PR from STA-5698's written "Suggested direction" without first checking whether a
That objection applies to this PR unchanged. The reboot case is not hypothetical: after any host #16843 also recorded why client-side detection was abandoned in general:
And a live repro could not produce the harm on Linux at all: The sanctioned fixes already exist as open PRs, both green and both unreviewed:
Those are prevention on the host, which is what #16843 concluded to do. What is still worth keeping hereTwo things, and I would not want them lost with the PR:
Also noted: Recommendation: close this in favour of #16894 + #16895, and split the |
|
SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support. Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was fixed. |
|
Thanks @brennanb2025 — the relay itself is gone, but the idea behind this (don't auto-resume an agent when the host's "terminal not found" was never observed as a real exit) still applies to managed hosts and paired runtimes. I've captured it on #13716 with credit to this PR; this one stays closed since its mechanism was relay-specific. |
What this fixes (ELI5)
Orca keeps a small helper process — the relay — running on your SSH host. It owns your remote terminals, and Orca reconnects to it when you come back.
When Orca reconnects and the relay answers "I don't have that terminal", Orca starts a fresh shell and replays whatever started the original terminal — the agent launch, the
claude --resume …argv, the startup command. On a normal cold restore that is exactly right: your agent comes back.But the relay can be replaced while you're away (an Orca upgrade, a host reboot, host-side cleanup). The replacement relay truthfully says "I don't have that terminal" — it never did. Meanwhile the old relay's shell may still be alive on the host as an orphan. Orca then replayed the resume, and you got a second agent running against the same worktree, fighting the first one over the same session state.
After this change, Orca checks how old the answering relay is before believing it.
relay.statusalready reports the daemon'suptimeMs. A daemon that has only been up 5 minutes cannot have owned a binding created 2 hours ago — so its "it's absent" answer proves nothing about that process. In that case Orca:launchAgent/ the resume argv /command,A plain shell is recoverable. A duplicate agent racing an orphan over one worktree is not.
Before / after
relay.statustimes out / rejects / errorsrelay.statusanswers, nouptimeMs(older host)Verdict vocabulary
Per
docs/reference/ssh-execution-boundary.md, the vocabulary stays exactlylive/unverifiable/exited. This change narrows one specific case fromexitedtounverifiable: a positive absence answer from a daemon that provably never held the binding is not positive evidence about that process.Silence is never promoted to a verdict. Every one of these leaves today's behavior byte-for-byte unchanged, by construction — each is an early
return false:requestHostRpc(optional call →undefined)relay.statusrejects, times out, or throws (catch → return false)uptimeMsis absent, non-numeric, non-finite, or negativeOnly an answer that arrives and is demonstrably younger suppresses the resume.
On the clock comparison
uptimeMsis the host's own elapsed-time counter; binding age is the client's elapsed time since the lease'screatedAt. Both are durations, so this compares two independently measured elapsed times — no clock-offset correction is possible or needed, and no wall-clock sync between client and host is assumed. A 30s slack (RELAY_AGE_CLOCK_SLACK_MS) absorbs jitter and the gap between daemon start and the first binding write.Remote wire compatibility
Confirmed against
docs/reference/remote-wire-compatibility.md: no wire change.relay.statusis called with{}exactly asskill-ssh-relay-client.tsalready does.uptimeMsis already published atsrc/relay/relay-daemon.ts:131.agentResumeUnavailablealready exists in the preload/renderer contract (src/preload/api/pty-api.ts:68) and is already produced byipc/spawn-commit.tsfor the Codex resume path. It is added to main'sPtySpawnResultand rides the existing IPC response spread. The runtime spawn response builds an explicit field whitelist (id,incarnationId,stablePaneOwner,agentSessionEnsure), so the flag does not reach the remote wire.An older host simply omits
uptimeMs→ no verdict → unchanged behavior.Failing-first proof
Production reverted (
git checkoutthe 4 modified files +rmthe new module), new test file kept:(The suite has since grown to 12 tests with two added coverage cases; the three suppression tests are the ones that can fail pre-fix.)
Honest note on the other tests. The task asked that every new test fail pre-fix. Only the three suppression tests can: the remaining nine pin "behavior is unchanged" (older relay, rejection, missing
uptimeMs, non-object reply, no lease, no host RPC, no startup intent, sub-slack gap, spawn never gated). A test asserting that today's behavior is preserved cannot fail before the change — that is what it means. Their value is proven by the ablation table below instead: each goes red when the gate is made too permissive. I have not claimed failing-first for them.Ablation table
Each production hunk reverted individually against the 12-test suite:
onRelayPositiveAbsence)spawnForStablePanecarriesStartupIntentguardansweringRelayPredatesBindingguardstripStartupIntentagentResumeUnavailableflagage === null)uptimeMstype guardrelay.statusfailurecatchcreatedAtlookupagent_startedgatemarkClaudePtySpawnedgateagent_started/ claude-marker gatesH13–H15 are uncovered and I am saying so rather than papering over it. They are three one-line consequential gates: a suppressed resume produced a plain shell, so
agent_startedtelemetry and the Claude-launch marker must not fire for an agent that never started. Without them this change would introduce a falseagent_started. Covering them needs a fullsetupPtyIpcSuiterun with a registered SSH provider, a lease store, and a relay-absence rejection driven throughexecutePtyIpcSpawn— disproportionate to three one-line conditions, so I left them uncovered rather than write a test that only restates the condition.Note on H10: my first mutation (
status = status ?? {}) left the suite green because it re-introduced a null guard. True deletion is red. Reporting both because the weak mutation is the kind that makes an ablation table lie.Gates
pnpm tc— exit 0oxlint(incl.--type-awareand react-doctor configs) on all changed files — clean, nomax-linesdisable added (the fallback body was extracted into the new module to stay under 300)npx oxfmt --write <changed paths>only — neverpnpm formatgit diff --check— cleanpnpm test src/main/ipc/pty— 10 pre-existing failures on both the clean tree and this branch (identical set, inpty-spawn-env-agent-overlays,pty-login-shell-startup-commands,pty-serializer-settlement-mapping,pty-spawn-env-codex-home-routing); this branch adds 12 passing tests (594 → 606 passing)What I did NOT verify
spawnForStablePane.agentResumeUnavailable→showSessionRestoredBanner('resume-unavailable')path rather than adding a new surface, but I did not visually confirm it end to end.spawnForStablePane). The banner only reaches the renderer on the IPC path, because the runtime spawn response is an explicit whitelist and adding the field there would be a wire change this ticket forbids. A paired-runtime user gets the plain shell without the banner.createdAtand recycled PTY ids.upsertSshRemotePtyLeasepreserves the oldestcreatedAtwhen a relay recycles apty-Nid (see the STA-3077 note inssh-pty-lease-operations.ts). That biases binding age older, i.e. toward suppression. I judged that acceptable — the conservative direction here is a plain shell — but I did not measure how often it fires in practice.relay.statusround-trip. It is bounded at 2s and only runs on the absence fallback when startup intent is present, but I did not time it against a real relay.Relationship to the other STA-5698 PRs
This is a different approach from the two open siblings, and deliberately narrower:
requestRelayProcessIdrequest field and persists it on the lease. That is additive-but-real wire surface.uptimeMs, whichrelay.statusalready publishes.uptimeMsis strictly weaker evidence than a minted identity (it cannot distinguish two daemons that both predate the binding), but it works against every existing host with no negotiation, including hosts that will never ship an identity field. These are alternatives, not stackable; whichever lands, the others should close. Flagging this rather than assuming — the merge choice is yours.Closes STA-5698.